package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 展示类型列表
     *
     * @return 类型集合
     */
    @Override
    public Result listTypes() {
        // 从Redis中获取
        String shopTypeKey = RedisConstants.CACHE_SHOP_KEY + "type";
        String shopTypesJsonInCache = stringRedisTemplate.opsForValue().get(shopTypeKey);
        if (StrUtil.isNotBlank(shopTypesJsonInCache)) {
            List<ShopType> shopTypes = JSONUtil.toList(shopTypesJsonInCache, ShopType.class);
            return Result.ok(shopTypes);
        }

        // Redis中未命中则从数据库中查询并存入Redis
        List<ShopType> shopTypesInDb = this.list();
        if (CollectionUtil.isEmpty(shopTypesInDb) && shopTypesInDb == null) {
            return Result.fail("未查询到数据！");
        }
        String shopTypesJsonInDb = JSONUtil.toJsonStr(shopTypesInDb);
        stringRedisTemplate.opsForValue().set(shopTypeKey, shopTypesJsonInDb);
        // 设置缓存过期时间为30M
        stringRedisTemplate.expire(shopTypeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypesInDb);
    }
}
